package com.igoal.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.igoal.entity.Comment;
import com.igoal.entity.ComponentEnum;
import com.igoal.web.Constants;

@Repository("commentDAO")
public class CommentDAOImpl extends GenericDaoHibernate<Comment, Long> implements CommentDAO {

	public CommentDAOImpl() {
		super(Comment.class);
	}

	public List<Comment> getAllCommentsBefore(Long componentId, ComponentEnum component, Date updateBefore) {
		DetachedCriteria dc = DetachedCriteria.forClass(Comment.class);
		dc.add(Restrictions.eq("componentId", componentId));
		dc.add(Restrictions.eq("component", component));
		if (updateBefore != null) {
			dc.add(Restrictions.lt("updateDate", updateBefore));
		}
		dc.addOrder(Order.desc("updateDate"));
		return findByCriteria(dc);
	}

	public Map<Integer, Object> countCommentsOfComponent(Long componentId, ComponentEnum component) {
		DetachedCriteria dc = DetachedCriteria.forClass(Comment.class);
		dc.add(Restrictions.eq("componentId", componentId));
		dc.add(Restrictions.eq("component", component));

		Map<Integer, Object> pages = countPage(dc, Constants.DEFAULT_COMMENT_PAGING_ORDER_PROPERTY, Constants.MAX_COMMENT_PER_PAGE);

		return pages;
	}

	public void addComments(List<Comment> comments) {
		for (Comment comment : comments) {
			save(comment);
		}
	}

	public List<Comment> getLatestComments(Long componentId, ComponentEnum component) {
		DetachedCriteria dc = DetachedCriteria.forClass(Comment.class);
		dc.add(Restrictions.eq("componentId", componentId));
		dc.add(Restrictions.eq("component", component));
		dc.addOrder(Order.desc("updateDate"));
		return findByCriteria(dc, 0, Constants.LATEST_COMMENT_SIZE);
	}

	public int countComments(Long componentId, ComponentEnum component) {
		DetachedCriteria dc = DetachedCriteria.forClass(Comment.class);
		dc.add(Restrictions.eq("component", component));
		dc.add(Restrictions.eq("componentId", componentId));
		List<Comment> comments = findByCriteria(dc);
		if (comments != null) {
			return comments.size();
		}
		return 0;
	}
}
